;
cmedit.CreTarget = (function($, window, document) {
	var thisContext;
	var topUtil = cmedit.global;
	var tenantId = "";
    var userId = "";
    var token = "";
    var userName = "";
	var CreTargetClass = function(){
	
	};
	
	CreTargetClass.prototype = {
		constructor:CreTargetClass,
		//初始化
		init:function(){
			thisContext = this;
			thisContext.initData();
			thisContext.initEvent();
		},
		//初始化数据
		initData : function(){
			var page = 1;
			//thisContext.getAppList();
			
			thisContext.initUserSession();
			thisContext.initColumn();
			thisContext.listCreTargetByCondition(page);
		},
		
		//初始化用户信息
		initUserSession: function () {
        	token = cmedit.global.getParameterFromUrl("token");
        	userId = cmedit.global.getParameterFromUrl("userId");
        	userName = cmedit.global.getParameterFromUrl("userName");
        	tenantId = cmedit.global.getParameterFromUrl("tenantId");
        	
        	if(!cmedit.global.isNotEmpty(token)){
        		alert("token为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userId)){
        		alert("userId为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userName)){
        		alert("userName为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(tenantId)){
        		alert("tenantId为空");
        		return false;
        	}
        },
        
        initColumn : function(){
        	var postData = {
        		key : window.localStorage.getItem("portalKey")
        	};
        	thisContext.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.releasePath+"UserInfoController/getUserColumnByUserId",
				data : postData,
				success: function(data) {
					if(data.status) {
						var columnList = data.data;
			     		for(var i = 0;i < columnList.length;i++){
							var option = "<option value=\"" + columnList[i].id+ "\">" + columnList[i].name + "</option>";
							$("#columnSelect").append(option);
						}
					}else{
						alert("初始化栏目失败");
					}
				}
			});
        },
		//初始化事件
		initEvent : function(){
			//点击上面的页签切换
			$("#addPara").on('click',function(){
				$('#addPara').addClass('refe_on');
				thisContext.changeToForm();
			});
			
			$("#sysPara").on('click',function(){
				$('#sysPara').addClass('refe_on');
				$('#addPara').removeClass('refe_on');
				$('#upPara').removeClass('refe_on');
				$('.refe_deploy').show();
				$('.refe_new').hide();
			});
			
			$("#upPara").on('click',function(){
				$('#upPara').addClass('refe_on');
				thisContext.changeToForm();
			});
			
			//新增参数点击按钮
			$('#addParameter').on('click',function(){
				thisContext.clearForm();
				thisContext.changeTab();
			});
			
			//保存新建参数按钮
			$('#savePara').on('click',function(){
				if(thisContext.check()){
					thisContext.createOrUpdateCreTarget();
				}
			});
			
			
			//删除参数点击按钮
			$('#delParameter').on('click',function(){
				var msg = "确认要删除该签发配置？";
				var systemParameterIds = thisContext.getSelectRows();
				if(systemParameterIds.length == 0){
					alert("请选择要删除的参数");
					return;
				}
				if(thisContext.alertChoice(msg)){
					thisContext.deleteCreTarget(systemParameterIds);
				}
				return;
			});
			
			//根据修改参数点击按钮
			$('#updatePara').on('click',function(){
				var systemParameterIds = thisContext.getSelectRows();
				if(systemParameterIds.length > 1){
					alert("只能选择一个参数进行修改！")
				} else if (systemParameterIds.length == 0){
					alert("请选择一个参数进行修改！")
				} else{
					thisContext.changeUpTab();
					var parameterId = systemParameterIds[0];
					//thisContext.selectSystemParameterById(parameterId);
					thisContext.getParameterById(parameterId);
					
				}
			});
			
			$('#cancel').on('click',function(){
				thisContext.changeTabBack();
				thisContext.clearForm();
			});
			
			//搜索
			$('.deploy_search').on('click',function(){
				thisContext.listCreTargetByCondition(1);
			});
			
			//搜索框回车事件
			$('#firstname').on('keypress',function(){
				if(event.keyCode==13){  
					thisContext.listCreTargetByCondition(1); 
				   }   
			});
			
			//全选反选
			$("#all").on('click',function(){
			    if(this.checked){   
			        $("#sysParametersTable :checkbox").prop("checked", true);  
			    }else{   
			    	$("#sysParametersTable :checkbox").prop("checked", false);
			    }   
			});
			
			//全选之后点其中一个,全选状态取消
			$("#creTargetTable ").on('click',':checkbox',function(){
            	var chknum = $("#creTargetTable :checkbox").size();
            	var chk = 0;
            	$("#creTargetTable :checkbox").each(function () {  
                    if($(this).prop("checked")==true){
            			chk++;
            		}
                });
            	if(chknum==chk){//全选
            		$("#all").prop("checked",true);
            	}else{//不全选
            		$("#all").prop("checked",false);
            	}
            });
			
			//表单验证
			$("#creServiceName").blur(function(){
				thisContext.checkService();
			});
			
			$("#creTargetName").blur(function(){
				thisContext.checkTarget();
			});
		},
		
		//新增或者修改系统参数
		createOrUpdateCreTarget : function(){
			var creTargetGuid = $('#creTargetGuid').val();
			var creServiceName = $('#creServiceName').val();
			var creTargetName = $('#creTargetName').val();
			var columnId = $('#columnSelect').val();
			var columnName = $("#columnSelect").find("option:selected").text();
			var creTargetHint = $('#creTargetHint').val();
			var postData = {
				"creTargetGuid":creTargetGuid,
				"creServiceName":creServiceName,
				"creTargetName":creTargetName,
				"columnId":columnId,
				"columnName" : columnName,
				"creTargetHint" : creTargetHint,
				"creTargetType" : 4,//稿件类型，通稿稿件设置为4.
			};
						
			thisContext.ajaxRequest({
				async : true,
				url : cmedit.global.releasePath
				+ "CreTargetController/putOrPostCreTarget",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						$('.refe_deploy').show();
						$('.refe_new').hide();
						$('#sysPara').addClass('refe_on');
						$('#addPara').removeClass('refe_on').hide();
						thisContext.listCreTargetByCondition(1);
					} else {
						alert(data.msg);
					}
				}
			});
		},
		
		//删除cre签发配置
		deleteCreTarget : function(creTargetGuids){
			var postData = {
				"creTargetGuids" : JSON.stringify(creTargetGuids)
			};
			
			thisContext.ajaxRequest({
				async : true,
				url : cmedit.global.releasePath
						+ "CreTargetController/deleteCreTarget",
				type : 'POST',
				data : postData,
				success : function(data) {
					if (data.status == true || data.status == 'true') {
						thisContext.initData();
					} else {
						alert(data.msg);
					}
				}
			})

		},
		
		//根据各种条件，分页查询cre签发配置
		listCreTargetByCondition : function(page){
			var creServiceName = $('#firstname').val();
			var tenantType = "0";
			var currentPage = page;
			var pageSize = "10";
			var postData = {
				"currentPage":currentPage,
				"pageSize" : pageSize,
				"creServiceName" : creServiceName,
			};
			
			thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.releasePath
				+ "CreTargetController/getCreTargetByPage",
				type : 'POST',
				data : postData,
				beforeSend: function (XHR) {
                    XHR.setRequestHeader("userId", userId);
                    XHR.setRequestHeader("tenantId", tenantId);
                    XHR.setRequestHeader("token", token);
                    XHR.setRequestHeader("userName", userName);
                },
				success : function(data){
					if (data.status == true || data.status == 'true') {
						thisContext.showData(data);
						thisContext.showPages(data);
					} else {
						alert(data.msg);
					}
				}
			});
			
		},
		
		//展示数据
		showData : function(data){
			var list = data.data.list;
			var data = {
				list : list
			};
			var creTargethtml = template('creTarget_table', data);
			$('#creTargetTable').html(creTargethtml);
		},
		
		//填充表单
		getParameterById : function(parameterId){
			var tr = $("#" + parameterId + "");
			var creTargetGuid = parameterId;
			var creServiceName = tr.find('td').eq(1).text();
			var creTargetName = tr.find('td').eq(2).text();
			var creTargetHint = tr.find('td').eq(3).text();
			var columnId = tr.find('td').eq(4).text();
			var columnName = tr.find('td').eq(5).text();
			var length = $("#columnSelect option").length;
			$("#columnSelect option").each(function(){
				if($(this).val() == tr.find('td').eq(4).text()){
					$(this).attr("selected",true);
				}
			})
			$('#creTargetGuid').val(creTargetGuid);
			$('#creServiceName').val(creServiceName);
			$('#creTargetName').val(creTargetName);
			$('#creTargetHint').val(creTargetHint);
			$('#columnId').val(columnId);
			$('#columnName').val(columnName);
		},
		
		ajaxRequest: function (opts) {
            // 一.设置默认参数
            var defaults = {
                url: '',
                type: '',
                data: '',
                cache: true,
                async: false,
                dataType: 'json',
//                contentType: "application/json;charset=UTF-8",
                success: function () {
                },
                error: function () {
                }
            };

            // 二.用户参数覆盖默认参数
            for (var key in opts) {
                defaults[key] = opts[key];
            }
            
            // 三.开始组装ajax
            $.ajax({
                url: defaults.url,
                type: defaults.type,
                data: defaults.data,
                async: defaults.async,
                cache: defaults.cache,
                dataType: defaults.dataType,
                contentType: defaults.contentType,
                beforeSend: function (XHR) {
                    XHR.setRequestHeader("userId", userId);
                    XHR.setRequestHeader("userName", encodeURIComponent(userName));
                    XHR.setRequestHeader("tenantId", tenantId);
                    XHR.setRequestHeader("token", token);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("错误信息" + errorThrown.toString());
                },
                success: defaults.success
            });
        },
		
		//展示页码
		showPages : function(data){
			var pages = data.data;
			var data = {
				pages : pages
			}
			var pagehtml = template('parameter_page', data);
			$('#paging').html(pagehtml);
		},
		//获取选中的参数
		getSelectRows : function(){
			var rows = [];
	        $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', '#sysTable').each(function(){
	            rows.push($(this).val());
	        });
	        return rows;
		},
		
		//新增标签页切换
		changeTab : function(){
			$('#addPara').addClass('refe_on').show();
			$('#upPara').removeClass('refe_on').hide();
			thisContext.changeToForm();
		},
		
		//修改标签页切换
		changeUpTab : function(){
			$('#upPara').addClass('refe_on').show();
			$('#addPara').removeClass('refe_on').hide();
			thisContext.changeToForm();
		},
		
		/**
		 * 切换到表单页面
		 */
		changeToForm : function(){
			$('#sysPara').removeClass('refe_on');
			$('.refe_deploy').hide();
			$('.refe_new').show();
		},
		//标签切回
		changeTabBack : function(){
			$('#sysPara').addClass('refe_on');
			$('#addPara').removeClass('refe_on').hide();
			$('#upPara').removeClass('refe_on').hide();
			$('.refe_deploy').show();
			$('.refe_new').hide();
		},
		//清空表单数据
		clearForm : function(){
			$('#creTargetGuid').val('');
			$('#creServiceName').val('');
			$('#creTargetName').val('');
			$('#columnId').val('');
			$('#columnName').val('');
			$('#creTargetHint').val('');
		},
		
		//弹出框
		alertChoice : function(msg){
			if(confirm(msg)) 
			  { 
			    return true; 
			  } 
			  return false;
		},
		
		//检查服务名称是否为空
		checkService : function(){
			var service = $("#creServiceName").val();
			//var cname = $("#cname").val();
			if(service == ''){
				$("#checkService").html("服务名称不能为空");
				return false;
			}else{
				$("#checkService").html("");
				return true;
			}
		},
		
		//检查签发名称是否为空
		checkTarget : function(){
			var target = $("#creServiceName").val();
			//var cname = $("#cname").val();
			if(target == ''){
				$("#checkTarget").html("签发名称不能为空");
				return false;
			}else{
				$("#checkTarget").html("");
				return true;
			}
		},
		
		
		//检查参数代码是否为空
		/*checkCode : function(){
			var code = $("#parameterCode").val();
			var ccode = $("#ccode").val();
			if(code == ''){
				$("#checkCode").html("参数代码不能为空");
				return false;
			}else if(!(code == ccode) && thisContext.exsitCode(code)){
				$("#checkCode").html("参数代码已存在，请重新输入");
				return false;
			}else{
				$("#checkCode").html("");
				return true;
			}
		},*/
		
		exsitCode : function(code){
			var trList = $("#sysParametersTable").children("tr");
			for(var i=0;i<trList.length;i++){
				var tdArr = trList.eq(i).find("td");
				var ccode = tdArr.eq(2).text();
				if(code == ccode){
					return true;
				}
			};
			return false;
		},
		
	
		check : function(){
			if(thisContext.checkService() && thisContext.checkTarget()){
				return true;
			}else{
				return false;
			}
		}
	};
	return new CreTargetClass();
})(jQuery, window, document);

$(cmedit.CreTarget.init());